import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

/**
 * @Author: lcq
 * @Date: 2024-12-28 11:03:04
 * @brief: 检查更新
 * @param {*} path
 * @return {*}
 */
export default function update(path = '') {
  return new Promise((resolve, reject) => {
    const router = useRouter()
    // 以下变量用于销毁监听事件
    let updateAvailable = null
    let downloadProgress = null
    let updateDownloaded = null
    let updateNotAvailable = null
    let updateError = null
    app.sendMessage('check-update')
    // 检测到新版本
    updateAvailable = app.onMessage('update-available', () => {
      resolve()
      ElMessageBox.confirm('检测到新版本，是否立即更新？', '提示', {
        confirmButtonText: '更新',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 下载新版本
          app.sendMessage('update-app')
          downloadProgress = app.onMessage('download-progress', (res) => {
            console.log('res', res.percent)
          })
          updateDownloaded = app.onMessage('update-downloaded', () => {
            ElMessage({
              message: '新版本下载完成, 安装中...',
              type: 'success'
            })
            downloadProgress()
            updateDownloaded()
          })
        })
        .catch(() => {
          // 取消更新
          path != '' && router.replace(path)
        })
        .finally(() => {
          updateAvailable()
        })
    })

    // 无新版本
    updateNotAvailable = app.onMessage('update-not-available', () => {
      path != '' && router.replace(path)
      updateNotAvailable()
      updateAvailable()
      updateError()
      reject()
    })
    updateError = app.onMessage('update-error', () => {
      path != '' && router.replace(path)
      updateNotAvailable()
      updateAvailable()
      updateError()
      reject()
    })
  })
}
